#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <QFileDialog>
#include <QDir>
#include <QMediaPlayer>
#include <QAudioOutput>
#include <QUrl>
#include <QSlider>
#include <QMouseEvent>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , volumeLabel(new QLabel(this))
{
    ui->setupUi(this);

    MainWindow::setWindowTitle("音乐播放器");
    QIcon appIcon(":/format.ico");
    MainWindow::setWindowIcon(appIcon);

    //初始化图标
    playIcon.addFile(":/assets/pause.png"); // 加载播放图标
    pauseIcon.addFile(":/assets/play.png"); // 加载暂停图标
    ui ->pushButton_4->setIcon(pauseIcon); // 初始设置为播放图标



    //如何播放音乐 先加载模块multimedia
    //先new一个output
    this -> out = new QAudioOutput(this);
    //再来一个媒体播放对象
    this -> mediaPlayer = new QMediaPlayer(this);
    out -> setVolume(0.5);
    mediaPlayer->setAudioOutput(this -> out);

    // 初始化音量滑块
    volumeSlider = new QSlider(Qt::Vertical, this);
    volumeSlider->setRange(0, 100); // 设置音量范围从0到100
    volumeSlider->setValue(out -> volume() * 100); // 初始音量设置为50
    volumeSlider->hide(); // 初始时隐藏滑块
    isVolumeSliderVisible = false;
    // 连接滑块的信号到槽以改变音量
    connect(volumeSlider, &QSlider::valueChanged, this, &MainWindow::onVolumeChanged);

    //获取当前媒体的时长 通过信号关联获取
    connect(mediaPlayer,&QMediaPlayer::durationChanged, this,[=](qint64 duration){
        ui -> totalLabel -> setText(QString("%1:%2").arg(duration/1000/60,2,10,QChar('0')).arg(duration/1000%60,2,10,QChar('0')));
        ui -> playCourseSlider -> setRange(0, duration);
    });

    //获取当前播放时长
    connect(mediaPlayer,&QMediaPlayer::positionChanged,this,[=](qint64 pos){
        ui -> curLabel -> setText(QString("%1:%2").arg(pos/1000/60,2,10,QChar('0')).arg(pos/1000%60,2,10,QChar('0')));
        ui -> playCourseSlider -> setValue(pos);
    });
    //拖动滑块，让音乐播放的进度改变
    connect(ui -> playCourseSlider,&QSlider::sliderMoved,mediaPlayer,&QMediaPlayer::setPosition);

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_pushButton_clicked()
{
    // //打开文件对话框，让用户选择音乐所在的目录
    // QString path = QFileDialog::getExistingDirectory(this,"请选择音乐所在的目录","C:\\CloudMusic");
    // //根据 选择的路径，获取里面的所有的mp3和wav文件
    // QDir dir(path);
    // QStringList musicList = dir.entryList(QStringList() << "*.mp3" << "*.wav");
    // //把音乐名字放到listWidget展示
    // ui -> listWidget -> addItems(musicList);
    // //默认选中第一个音乐
    // ui -> listWidget -> setCurrentRow(0);
    // //把音乐的完整路径保存起来
    // for(QString file : musicList){
    //     playList.append(QUrl::fromLocalFile(path + "/" + file));
    // }
    // if (isVolumeSliderVisible) {
    //     isVolumeSliderVisible = false;
    //     volumeSlider->hide();
    //     volumeLabel->hide();
    // }
    // 打开文件对话框，让用户选择音乐文件
    QStringList files = QFileDialog::getOpenFileNames(this, tr("请选择音乐文件"), "C:\\Users", tr("音乐文件 (*.mp3 *.wav)"));

    // 如果用户没有选择任何文件，直接返回
    if (files.isEmpty())
        return;

    // 把音乐文件名添加到列表中展示
    ui->listWidget->addItems(files);

    // 把音乐的完整路径保存起来
    for(const QString& file : files){
        playList.append(QUrl::fromLocalFile(file));
    }

    // 默认选中第一个音乐
    ui->listWidget->setCurrentRow(0);

    // 如果音量滑块可见，则隐藏
    if (isVolumeSliderVisible) {
        isVolumeSliderVisible = false;
        volumeSlider->hide();
        volumeLabel->hide();
    }
}


void MainWindow::on_pushButton_4_clicked()
{
    if(playList.empty()){
        return;
    }
    QIcon newIcon;
    // MediaStatus status = mediaPlayer -> mediaStatus();
    switch(mediaPlayer -> playbackState())
    {
    case QMediaPlayer::PlaybackState::StoppedState: //停止状态
    {

        //如果没有播放，播放当前选中的音乐
        //获取选中的音乐的行数
        curPlayIndex = ui -> listWidget -> currentRow();
        //给播放器设置音乐
        mediaPlayer->setSource(playList.at(curPlayIndex));
        mediaPlayer->play();
        newIcon = playIcon; // 设置为暂停图标
    }
        break;
    case QMediaPlayer::PlaybackState::PlayingState: //正在播放状态
        mediaPlayer->pause();//暂停
        newIcon = pauseIcon;
        break;
    case QMediaPlayer::PlaybackState::PausedState: //暂停状态
        mediaPlayer->play();
        newIcon = playIcon;
        break;
    }
    ui ->pushButton_4->setIcon(newIcon);
    if (isVolumeSliderVisible) {
        isVolumeSliderVisible = false;
        volumeSlider->hide();
        volumeLabel->hide();
    }
}


//上一曲
void MainWindow::on_pushButton_3_clicked()
{
    ui -> pushButton_4 -> setIcon(pauseIcon);
    if(curPlayIndex == 0){
        curPlayIndex = playList.size() - 1;
    } else {
        curPlayIndex = (curPlayIndex - 1) % playList.size();
    }
    ui -> listWidget -> setCurrentRow(curPlayIndex);
    mediaPlayer->setSource(playList[curPlayIndex]);
    mediaPlayer->play();
    ui -> pushButton_4 -> setIcon(playIcon);
    if (isVolumeSliderVisible) {
        isVolumeSliderVisible = false;
        volumeSlider->hide();
        volumeLabel->hide();
    }
}

//下一曲
void MainWindow::on_pushButton_5_clicked()
{
    ui -> pushButton_4 -> setIcon(pauseIcon);
    //让listWidget选中下一行
    curPlayIndex = (curPlayIndex + 1) % playList.size();
    ui -> listWidget -> setCurrentRow(curPlayIndex);
    mediaPlayer->setSource(playList[curPlayIndex]);
    mediaPlayer->play();
    ui -> pushButton_4 -> setIcon(playIcon);
    if (isVolumeSliderVisible) {
        isVolumeSliderVisible = false;
        volumeSlider->hide();
        volumeLabel->hide();
    }
}

//播放选中的音乐
void MainWindow::on_listWidget_doubleClicked(const QModelIndex &index)
{
    ui -> pushButton_4 -> setIcon(pauseIcon);
    curPlayIndex = index.row();
    mediaPlayer->setSource(playList[curPlayIndex]);
    mediaPlayer->play();
    ui -> pushButton_4 -> setIcon(playIcon);
    if (isVolumeSliderVisible) {
        isVolumeSliderVisible = false;
        volumeSlider->hide();
        volumeLabel->hide();
    }
}

/*
 * 点击音量键，显示音量进度条
 */
void MainWindow::on_pushButton_6_clicked()
{
    if (!isVolumeSliderVisible) {
        // 显示滑块并设置其位置（根据需要调整）
        volumeSlider->setGeometry(QRect(this->width() - 75, 420, 20, 100));
        volumeSlider->show();
        isVolumeSliderVisible = true;
        volumeLabel->setGeometry(QRect(this->width() - 90,380,60,60));
        volumeLabel->show();
        volumeLabel->setText(QString("音量: %1%").arg(out->volume() * 100));
    } else {
        // 隐藏滑块
        volumeSlider->hide();
        isVolumeSliderVisible = false;
        volumeLabel->hide();
    }
}

void MainWindow::onVolumeChanged(int value) {
    // qDebug()<<"音量变化：" << value;
    qreal volume = static_cast<qreal>(value) / 100.0;
    out->setVolume(volume);
    volumeLabel->setText(QString("音量: %1%").arg(value));
}

void MainWindow::mousePressEvent(QMouseEvent *event) {
    // 检查鼠标点击的位置是否在音量滑块之外
    QPoint pos = event->pos();
    QRect sliderRect = volumeSlider->geometry();
    if (!sliderRect.contains(pos)) {
        // 如果不在滑块范围内，隐藏音量滑块
        volumeSlider->hide();
        isVolumeSliderVisible = false;
        volumeLabel->hide(); // 隐藏音量标签
    }
    // 传递事件给父类处理
    QMainWindow::mousePressEvent(event);
}


